package com.atguigu.crowd.handler;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpSession;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.atguigu.crowd.api.MySQLRemoteService;
import com.atguigu.crowd.api.RedisRemoteService;
import com.atguigu.crowd.config.ShortMessageProperties;
import com.atguigu.crowd.constant.CrowdConstant;
import com.atguigu.crowd.entity.po.MemberPO;
import com.atguigu.crowd.entity.vo.MemberLoginVO;
import com.atguigu.crowd.entity.vo.MemberVO;
import com.atguigu.crowd.util.CrowdUtil;
import com.atguigu.crowd.util.ResultEntity;

@Controller
public class MemberHandler {
	
	@Autowired
	private ShortMessageProperties smp;
	
	@Autowired
	private RedisRemoteService rms;
	
	@Autowired
	private MySQLRemoteService mrs;
	
	@RequestMapping("/auth/member/logout")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:http://127.0.0.1/";
	}
	
	
	@RequestMapping("/auth/member/do/login")
	public String login(@RequestParam("loginacct") String loginacct, @RequestParam("userpswd") String userpswd , ModelMap modelMap ,HttpSession session) {
		ResultEntity<MemberPO> resultEntity = mrs.getMemberPOByLoginAcctRemote(loginacct);
		if(ResultEntity.FAILED.equals(resultEntity.getResult())) {
			modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, resultEntity.getmessage());
			return "member-login";
		}
		MemberPO memberPO = resultEntity.getData();
		if(memberPO == null) {
			modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_LOGIN_FAILED);
			return "member-login";
		}
		String sqlPwd = memberPO.getUserpswd();
		BCryptPasswordEncoder bpe = new BCryptPasswordEncoder();
		boolean matche = bpe.matches(userpswd, sqlPwd);
		if(!matche) {
			modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_LOGIN_FAILED);
			return "member-login";
		}
		MemberLoginVO memberLoginVO = new MemberLoginVO(memberPO.getId(),memberPO.getUsername(),memberPO.getEmail());
		session.setAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER, memberLoginVO);
		return "redirect:http://127.0.0.1/auth/member/to/center/page";
	}
	
	
	@RequestMapping("/auth/to/member/register")
	public String register(MemberVO memberVO , ModelMap modelMap) {
		
		String phoneNum = memberVO.getPhoneNum();
		String key = CrowdConstant.REDIS_CODE_PREFIX + phoneNum;
		ResultEntity<String> redis = rms.getRedisStringValueByKeyRemote(key);
		
		if(ResultEntity.FAILED.equals(redis.getResult())) {
			modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, redis.getmessage());
			return "member-reg";
		}
		
		String redisCode = redis.getData();
		if(redisCode == null) {
			modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_CODE_NOT_EXISTS);
			return "member-reg";
		}

		String formCode = memberVO.getCode();
		if(!Objects.equals(formCode, redisCode)) {
			modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_CODE_INVALD);
			return "member-reg";
		}
		rms.removeRedisKeyRemote(key);
				
		BCryptPasswordEncoder bpe = new BCryptPasswordEncoder();
		String userPswd = memberVO.getUserpswd();
		String encoder = bpe.encode(userPswd);
		memberVO.setUserpswd(encoder);
		MemberPO memberPO = new MemberPO();
		BeanUtils.copyProperties(memberVO, memberPO);
		
		ResultEntity<String> save = mrs.saveMember(memberPO);
		if(ResultEntity.FAILED.equals(save.getResult())) {
			modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, save.getmessage());
			return "member-reg";
		}
		
		return "redirect:http://127.0.0.1/auth/member/to/login/page";
	}
	

	@ResponseBody
	@RequestMapping("/auth/member/send/short/message.json")
	public ResultEntity<String> sendMessage(@RequestParam("phoneNum") String phoneNum) {
		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < 4; i++) {
			int random = (int) (Math.random() * 10);
			builder.append(random);
		}
		String param = builder.toString();	//验证码
		ResultEntity<String> result = CrowdUtil.sendMessage(param, phoneNum, smp.getHost(), smp.getPath(),
				smp.getAppcode(), smp.getSign(), smp.getSkin());
		if(ResultEntity.SUCCESS.equals(result.getResult())) {
			String key = CrowdConstant.REDIS_CODE_PREFIX + phoneNum;
			ResultEntity<String> redis = rms.setRedisKeyValueRemoteWithTimeout(key, param, 5, TimeUnit.MINUTES);
			if(ResultEntity.SUCCESS.equals(redis.getResult())) {
				return ResultEntity.successWithoutData();
			}else {
				return redis;
			}
		}else {
			return result;
		}
	}
}
